import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Select } from 'antd';
import { Icon } from '@iconify/react';
import { useNavigate } from 'react-router-dom';
import { login, getAvailableTenants } from '@/api/auth';
import { useAuthStore } from '@/stores/useAuthStore';
import { useThemeStore } from '@/stores/useThemeStore';
import { useSettingsStore } from '@/stores/useSettingsStore';
import { useMessage } from '@/hooks';
import styles from './index.module.css';

interface LoginForm {
  tenantId?: string;
  email: string;
  password: string;
}

interface Tenant {
  id: string;
  name: string;
  subdomain: string;
}

const Login = () => {
  const navigate = useNavigate();
  const { setAuth } = useAuthStore();
  const { isDark, setMode } = useThemeStore();
  const { language, setLanguage } = useSettingsStore();
  const [form] = Form.useForm();
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const message = useMessage();
  const [needTenantSelect, setNeedTenantSelect] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const hostname = window.location.hostname;
    const isMainDomain = hostname === 'localhost' || hostname === '127.0.0.1' || hostname.includes('192.168');
    
    if (isMainDomain) {
      setNeedTenantSelect(true);
      fetchTenants();
    }
  }, []);

  const fetchTenants = async () => {
    try {
      const response = await getAvailableTenants();
      if (response.data.success && response.data.data) {
        const tenantList = response.data.data;
        setTenants(tenantList);
        
        // 如果有租户，默认选择第一个
        if (tenantList.length > 0) {
          form.setFieldsValue({ tenantId: tenantList[0].id });
        }
      }
    } catch (error: any) {
      console.error('获取租户列表失败:', error);
    }
  };

  const handleSubmit = async (values: LoginForm) => {
    try {
      setLoading(true);
      const response = await login(values.email, values.password, values.tenantId);
      
      if (response.data.success && response.data.data) {
        const { user, accessToken, refreshToken } = response.data.data;
        setAuth(user, accessToken, refreshToken);
        message.success('登录成功！');
        navigate('/');
      } else {
        message.error(response.data.message || '登录失败');
      }
    } catch (error: any) {
      message.error(error.message || '登录失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  const toggleTheme = () => {
    setMode(isDark() ? 'light' : 'dark');
  };

  const toggleLanguage = () => {
    setLanguage(language === 'zh-CN' ? 'en-US' : 'zh-CN');
  };

  return (
    <section className={styles.container}>
      {/* 极光背景 */}
      <div className={styles.aurora}>
        <div className={styles.auroraLayer1}></div>
        <div className={styles.auroraLayer2}></div>
        <div className={styles.auroraLayer3}></div>
      </div>

      {/* 工具栏 */}
      <div className="fixed bottom-6 right-6 z-20 flex gap-2 p-2 rounded-xl backdrop-blur-md bg-white/10 border border-white/20">
        <button
          onClick={toggleTheme}
          className="w-10 h-10 flex items-center justify-center bg-transparent border-none rounded-lg text-gray-700 text-lg cursor-pointer hover:bg-white/30 transition-all"
          title={isDark() ? '切换到浅色模式' : '切换到深色模式'}
        >
          <Icon icon={isDark() ? 'solar:sun-bold' : 'solar:moon-bold'} />
        </button>
        <button
          onClick={toggleLanguage}
          className="w-10 h-10 flex items-center justify-center bg-transparent border-none rounded-lg text-gray-700 text-lg cursor-pointer hover:bg-white/30 transition-all"
          title="切换语言"
        >
          <Icon icon="solar:global-bold" />
        </button>
      </div>

      <div className="w-full max-w-sm mx-auto px-5 relative z-10">
        <div className={styles.loginCard}>
          {/* Logo */}
          <div className="text-center mb-6">
            <div className="text-5xl mb-3 inline-block" style={{ color: 'var(--primary-color)' }}>
              <Icon icon="solar:shield-user-bold" />
            </div>
            <h2 className="text-2xl font-bold text-gray-800 mb-1">多租户管理系统</h2>
            <p className="text-gray-600 text-xs">Multi-Tenant SaaS Platform</p>
          </div>

          <Form
            form={form}
            onFinish={handleSubmit}
            layout="vertical"
            size="middle"
            autoComplete="off"
            initialValues={{
              email: 'admin@saas.com',
              password: 'Admin@123456',
            }}
          >
            {needTenantSelect && (
              <Form.Item
                name="tenantId"
                label={<span className="text-gray-700 font-medium text-sm">选择租户</span>}
                rules={[{ required: true, message: '请选择租户' }]}
              >
                <Select
                  placeholder="请选择租户"
                  suffixIcon={<Icon icon="solar:alt-arrow-down-linear" />}
                  options={tenants.map(t => ({
                    label: `${t.name} (${t.subdomain})`,
                    value: t.id,
                  }))}
                  className={styles.customSelect}
                />
              </Form.Item>
            )}

            <Form.Item
              name="email"
              label={<span className="text-gray-700 font-medium text-sm">账号</span>}
              rules={[
                { required: true, message: '请输入账号' },
                { type: 'email', message: '请输入有效的账号' },
              ]}
            >
              <Input
                prefix={<Icon icon="solar:user-linear" className="text-gray-400" />}
                placeholder="请输入账号"
                className={styles.customInput}
              />
            </Form.Item>

            <Form.Item
              name="password"
              label={<span className="text-gray-700 font-medium text-sm">密码</span>}
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password
                prefix={<Icon icon="solar:lock-password-linear" className="text-gray-400" />}
                placeholder="请输入密码"
                className={styles.customInput}
              />
            </Form.Item>

            <Form.Item className="mt-5 mb-0">
              <Button
                type="primary"
                htmlType="submit"
                block
                loading={loading}
                className={styles.submitButton}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </section>
  );
};

export default Login;
